package com.climb.moive.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class CommmonUtils {
    //将Map转换成为JavaBean
    public static <T> void parseBean(T obj, Map<String, String[]> map) {
        try {
            ConvertUtils.register(new Converter() {
                @Override
                public Object convert(Class clazz, Object value) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date result = null;
                    try {
                        result = format.parse(value.toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return result;
                }
            }, Date.class);

            BeanUtils.populate(obj, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //将Map转换成为JavaBean
    public static Map<String, String[]> parseUploadRequest(HttpServletRequest request) throws Exception {
        //保存request中的请求参数值
        Map<String, String[]> map = new HashMap<>();

        //设置图片的上传目录，如果没有就创建
        String savePath = request.getServletContext().getRealPath("/upload");
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }

        // Fileupload的使用
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        List<FileItem> list = upload.parseRequest(request);
        for (FileItem item : list) {
            if (item.isFormField()) {// 普通表单字段
                String name = item.getFieldName();
                String value = item.getString("UTF-8");//注意：默认是ISO8859-1，这里必须设置编码
                map.put(name, new String[]{value});
            } else {// 上传文件项
                String filename = item.getName();
                if (filename == null || filename.trim().equals("")) {
                    continue;
                }

                String suffix = filename.substring(filename.lastIndexOf(".") + 1);// 获得文件后缀名
                filename = UUID.randomUUID() + "." + suffix;//使用UUID作为文件名，可以防止文件重名

                InputStream in = item.getInputStream();
                FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                byte buffer[] = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.close();
                in.close();
                item.delete();// 删除临时文件

                map.put("picture", new String[]{filename});
            }
        }

        return map;
    }
    public static void delecOldPic(String picName,HttpServletRequest request) throws InterruptedException {
        //获取当前要删除文件的
        String savePath = request.getServletContext().getRealPath("/upload");
        File file = new File(savePath);
        /*如果文件夹不存在那么就不删它？这里得确定文件夹就是这个名字就在这个地方·*/
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("文件夹不存在或者已经更换");
            return;
        }
        /*删掉这个文件*/
        String picPath=savePath+"/"+picName;
        System.out.println(picPath);
        File delFile = new File(picPath);
        /*如果图片不存在就不管它*/
        if (!delFile.exists()) {
            System.out.println("图片不存在");
            return;
        }

        if (delFile.delete()){
            System.out.println("文件"+delFile+"删除成功！");
        }else{
            System.out.println("文件"+delFile+"删除失败！");
        }



    }
}
